package com.zhuoyue.common.aop.check.sms.code.lived;

import com.zhuoyue.common.exception.ErrorType;
import com.zhuoyue.common.exception.ZyServerException;
import com.zhuoyue.common.utils.SmsTpl;
import io.lettuce.core.RedisConnectionException;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;


/**
 * @author wjming
 * @ClassName: CheckSmsCodeLivedVerification
 * @Description: 用于验证码验证
 * @Date 2021-07-02 14:31
 */
@Aspect
@Component
public class CheckSmsCodeLivedVerification {

    @Autowired
    private RedisTemplate redisTemplate;

    @Before("@annotation(com.zhuoyue.common.aop.check.sms.code.lived.CheckSmsCodeLived)")
    public void checkCode(JoinPoint point) {

        // 获取方法签名
        MethodSignature methodSignature = (MethodSignature) point.getSignature();
        // 获取方法
        Method method = methodSignature.getMethod();
        CheckSmsCodeLived paramsTake = method.getAnnotation(CheckSmsCodeLived.class);
        // 获取注解参数名称
        String requestPhoneValue = paramsTake.requestPhoneValue();
        //获取参数值
        HttpServletRequest request = getHttpServletRequest();
        String orgCode = request.getHeader("organizationCode");
        String account = request.getParameter(requestPhoneValue);
        if (StringUtils.isEmpty(account)) {
            throw new ZyServerException(ErrorType.INVALID_PARAMS.getCode(), "手机号码不能为空");
        }
        try {
            //根据手机号和组织编码获取redis现有数据，如果没有,则Smscode为空
            String smsCode = (String) redisTemplate.opsForValue().get(SmsTpl.rdsTpl(account, orgCode) + "_1");
            //如果redis中数据不存在，则意味着该用户未合法注册，抛出异常
            if (smsCode == null || "".equals(smsCode)) {
                throw new ZyServerException(ErrorType.Sms_NotFoundError.getCode(), "需经过验证码验证");
            }
        } catch (RedisConnectionException exception) {
            throw new ZyServerException(ErrorType.Redis_Can_Not_Connection);
        }
        //删除redis中的验证码信息
        //redisTemplate.delete(SmsTpl.rdsTpl(account, orgCode));

    }

    private HttpServletRequest getHttpServletRequest() {
        //1.从header里面获取token
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes attributes = (ServletRequestAttributes) requestAttributes;
        return attributes.getRequest();
    }

}
